package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.commonutils.JwtUtils;
import com.commonutils.results;
import com.entity.SysUser;
import com.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/management")
@CrossOrigin
public class loginController {
    @Resource
    private SysUserService userService;

    @ApiOperation("登陆功能")
    @PostMapping("/login")
    public results loginUser(@RequestBody SysUser user){
        String username = user.getUsername();
        String password = user.getPassword();
        if (StringUtils.isEmpty(username)){
            return results.error("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)){
            return results.error("密码不能为空");
        }
        SysUser sysUser = userService.getOne(new QueryWrapper<SysUser>().eq("username", username));
        if (sysUser==null) {
            return results.error("用户不存在");
        }
        if (!password.equals(sysUser.getPassword())) {
            return results.error("密码不正确");
        }
        //账号状态，1为激活，0为未激活
        if (sysUser.getStatus()) {
            return results.error("账号已被禁用");
        }
        String token = JwtUtils.getJwtToken(sysUser.getId(), sysUser.getNickname());
        return results.ok().data("token",token);
    }

    @ApiOperation("根据token获取用户信息")
    @GetMapping("getMemberInfoByToken")
    public results getMemberInfoByToken(HttpServletRequest request){
        Integer memberId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        Map<String, Object> userInfo = userService.getUserInfoByToken(memberId);
        return results.ok().data(userInfo);
    }

    /**
     * 获取菜单
     * @return
     */
    @GetMapping("menu")
    public results getMenu(HttpServletRequest request){
        Integer memberId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        List<JSONObject> permissionList = userService.getMenu(memberId);
        return results.ok().data("permissionList", permissionList);
    }

    @PostMapping("logout")
    public results logout(){
        return results.ok();
    }














//    @PostMapping("/login")
//    public results login(){
//        return results.ok().data("token","admin");
//    }
//
//    @GetMapping("/info")
//    public results info(){
//        return results.ok().data("roles","[admin]").data("admin","admin").data("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//    }
}
